<template>
  <div class="dashboard-container">
    <!-- 企业管理 -->
    <!-- 搜索from表单 -->
    <div class="main">
      <el-form
        :model="enterprise"
        label-width="100px"
        class="form-container"
        ref="searchForm"
      >
        <div>
          <el-form-item
            label="标签名称"
            prop="tags"
          >
            <el-input
              v-model="enterprise.tags"
              placeholder="请输入"
              size="small"
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="城市"
            prop="province"
          >
            <el-select
              v-model="enterprise.province"
              placeholder="请选择"
              @change="changeCitySearch"
            >
              <el-option
                v-for="(item, i) in cityslist(citydatas)"
                :key="i"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="地区"
            prop="city"
          >
            <el-select
              v-model="enterprise.city"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, i) in district(enterprise.province,citydatas)"
                :key="i"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="企业简称"
            prop="shortName"
          >
          <el-input
            v-model="enterprise.shortName"
          />
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="状态"
            prop="state"
          >
            <el-select
              v-model="enterprise.state"
              placeholder="请选择"
            >
              <el-option label="禁用" :value="0"></el-option>
              <el-option label="启用" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="bnt">
          <el-button
            size="small"
            @click="eliminate"
          >
            清除
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="enterpriseSearch"
          >
            搜索
          </el-button>
        </div>
        <div></div>
        <div>
          <div class="add-user">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="small"
              @click="addUserPopup"
            >
              新增用户
            </el-button>
          </div>
        </div>
      </el-form>
      <!-- 新增用户 -->
      <el-dialog
        title="创建用户"
        :visible.sync="addUserVisible"
        @close="addUserClose"
      >
      <el-form
        :model="corporateInformation"
        label-width="150px"
        :rules="rules"
        ref="corporateForm"
        class="adduser-container"
      >
        <div>
          <el-form-item
            label="企业名称"
            prop="shortName"
          >
            <el-input
              v-model="corporateInformation.shortName"
              size="small"
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="所属公司"
            prop="company"
          >
            <el-input
              v-model="corporateInformation.company"
              size="small"
            />
            <p>
              https://www.tianyancha.com （在此可查询所属公司全称及简称）
            </p>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="城市地区"
            prop="province"
          >
            <div class="city">
              <div>
                <el-select
                  v-model="corporateInformation.province"
                  placeholder="请选择"
                  @change="changeCity"
                >
                  <el-option
                    v-for="(item, i) in cityslist(citydatas)"
                    :key="i"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </div>
              <div>
                <el-select
                  v-model="corporateInformation.city"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, i) in district(corporateInformation.province,citydatas)"
                    :key="i"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </div>
            </div>
          </el-form-item>
        </div>
          <div>
            <el-form-item
              label="方向（企业标签）"
              prop="tags"
            >
              <el-input
                v-model="corporateInformation.tags"
                size="small"
              />
            </el-form-item>
          </div>
          <div>
            <el-form-item
              label="备注"
              prop="remarks"
            >
              <el-input
                type="textarea"
                placeholder="请输入"
                v-model="corporateInformation.remarks"
                size="small"
              />
            </el-form-item>
          </div>
          <div>
            <el-form-item>
              <div class="add-bnt">
                <el-button
                  size="small"
                  @click="addUserClose"
                >
                  取消
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="addUserSubmit"
                >
                  确定
                </el-button>
              </div>
            </el-form-item>
          </div>
      </el-form>
      </el-dialog>
      <!-- 记录 -->
      <div class="record-container">
        <i class="el-icon-info"></i>
        共 {{ companyslist.total }} 条记录
      </div>

      <div class="derive-list">
        <my-table
          :table-props="{
            data: companyslist.items,
            border: true
          }"

          :columns="[
            { label: '序号', prop: 'index', align: 'center' },
            { label: '企业编号', prop: 'number', width: 80, align: 'center' },
            { label: '企业简称', prop: 'shortName', align: 'center' },
            { label: '标签', prop: 'tags', align: 'center'},
            { label: '创建者', prop: 'creatorID', align: 'center'},
            { label: '创建时间', prop: 'addDate', align: 'center'},
            { label: '备注', prop: 'remarks', align: 'center'},
            { label: '状态', prop: 'state', align: 'center' },
            { label: '操作', slotName: 'operators', align: 'center', width: 200},
          ]"
          :pagination-props="{
            background: true,
            layout: 'prev, pager, next, sizes, jumper',
            total: companyslist.total,
            pageSizes: [10, 20, 30, 50],
          }"
          :pagination-events="events"
        >
          <template
            v-slot:operators="scope"
          >
            <el-button
              type="primary"
              plain
              icon="el-icon-edit"
              circle
              @click="editUserPopup(scope.row)"
            />
            <el-tooltip class="item" effect="dark" :content="scope.row.state === '启用' ? '禁用' : '启用' " placement="top-start">
              <el-button
                :type="scope.row.state === '启用' ? 'warning' : 'success' "
                plain
                :icon="scope.row.state === '启用' ? 'el-icon-close' : 'el-icon-check' "
                circle
                @click="changeState(scope.row)"
              />
            </el-tooltip>
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              class="delete-user"
              circle
              @click="deleteCompany(scope.row.id)"
            />
          </template>
        </my-table>
      </div>
      <!-- 编辑用户 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="compileUserVisible"
      >
      <el-form
        :model="compileUser"
        label-width="150px"
        :rules="rules"
        ref="compileUserForm"
        class="adduser-container"
      >
        <div>
          <el-form-item
            label="企业名称"
            prop="shortName"
          >
            <el-input
              v-model="compileUser.shortName"
              size="small"
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="所属公司"
            prop="company"
          >
            <el-input
              v-model="compileUser.company"
              size="small"
            />
            <p>
              https://www.tianyancha.com （在此可查询所属公司全称及简称）
            </p>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="城市地区"
            prop="province"
          >
            <div class="city">
              <div>
                <el-select
                  v-model="compileUser.province"
                  placeholder="请选择"
                  @change="changeCompileUser"
                >
                  <el-option
                    v-for="(item, i) in cityslist(citydatas)"
                    :key="i"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </div>
              <div>
                <el-select
                  v-model="compileUser.city"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, i) in district(compileUser.province,citydatas)"
                    :key="i"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </div>
            </div>
          </el-form-item>
        </div>
          <div>
            <el-form-item
              label="方向（企业标签）"
              prop="tags"
            >
              <el-input
                v-model="compileUser.tags"
                size="small"
              />
            </el-form-item>
          </div>
          <div>
            <el-form-item
              label="备注"
              prop="remarks"
            >
              <el-input
                type="textarea"
                placeholder="请输入"
                v-model="compileUser.remarks"
                size="small"
              />
            </el-form-item>
          </div>
          <div>
            <el-form-item>
              <div class="add-bnt">
                <el-button
                  size="small"
                  @click="addUserClose"
                >
                  取消
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="compileUserSubmit"
                >
                  确定
                </el-button>
              </div>
            </el-form-item>
          </div>
      </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import * as addCompanysApi from '@/api/hmmm/companys'
import { datas, provinces, citys } from '@/api/hmmm/citys'
export default {
  name: 'Companys',
  data() {
    const validateNull = (rule, value, callback) => {
      if (!value  || value === '') {
        callback(new Error(this.$t('企业简称不能为空')))
      } else {
        callback()
      }
    }
    const validateCompany = (rule, value, callback) => {
      if (!value  || value === '') {
        callback(new Error(this.$t('所属公司不能为空')))
      } else {
        callback()
      }
    }
    const validateCity = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('请选择省份')))
      } else {
        callback()
      }
    }
    const validateLabel = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('请输入标签')))
      } else {
        callback()
      }
    }
    const validateRemark = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('备注不能为空')))
      } else {
        callback()
      }
    }
    return {
      district: citys,
      cityslist: provinces,
      citydatas: datas,
      page: 1,
      pagesize: 10,
      events: {
        'size-change': this.handleSizeChange,
        'current-change': this.handleCurrentChange,
      },
      addUserVisible: false,
      compileUserVisible : false,
      // 搜索用户
      enterprise: {
        page: 1,
        pagesize: 10,
        tags: '',
        province: '',
        city: '',
        shortName: '',
        state: ''
      },
      // 添加用户
      corporateInformation: {
        city: '',
        company: '',
        isFamous: true,
        province: '',
        remarks: '',
        shortName: '',
        tags: ''
      },
      // 修改用户
      compileUser: {
        id: '',
        number: '',
        city: '',
        company: '',
        isFamous: true,
        province: '',
        remarks: '',
        shortName: '',
        tags: '',
      },
      rules: {
        shortName: [
          { required: true, trigger: 'blur', validator: validateNull },
        ],
        company: [
          { required: true, trigger: 'blur' , validator: validateCompany},
        ],
        province: [
          { required: true, trigger: 'blur' , validator: validateCity},
        ],
        tags: [
          { required: true, trigger: 'blur' , validator: validateLabel},
        ],
        remarks: [
          { required: true, trigger: 'blur' , validator: validateRemark},
        ]
      }
    }
  },
  watch: {
    enterprise: {
      handler(val) {
      },
      deep: true
    }
  },
  created() {
    this.uptateCompanysList({
      page: this.page,
      pagesize: this.pagesize
    })
  },
  computed: {
    ...mapState('companys',  [
      'companyslist'
    ]),
  },
  methods: {
    ...mapActions('companys', [
      'uptateCompanysList'
    ]),
    // 搜索企业
    enterpriseSearch() {
      const params = this.enterprise;
      // 循环params，如果为空，则删除该键值对
      for (const key in params) {
        if (params[key] === '') {
          delete params[key]
        }
      }
      this.uptateCompanysList(params)
      // 刷新页面
    },
    // 清除搜索条件
    eliminate() {
      this.$refs.searchForm.resetFields()
      this.uptateCompanysList({
        page: this.page,
        pagesize: this.pagesize
      })
    },
    // 搜索企业select
    changeCitySearch(val) {
      this.district(val,this.citydatas);
      // 区域反显
      const transition = this.district(val,this.citydatas)[0];
      this.enterprise.city = transition;
    },
    addUserPopup() {
      this.addUserVisible = true;
    },
    // 每页条数
    handleSizeChange(val) {
      this.pagesize = val;
      this.uptateCompanysList({
        page: this.page,
        pagesize: this.pagesize
      })
    },
    // 当前页数
    handleCurrentChange(val) {
      console.log(val);
      this.page = val;
      this.uptateCompanysList({
        page: this.page,
        pagesize: this.pagesize
      })
    },
    // 表单重置
    addUserClose() {
      this.addUserVisible = false;
      this.$refs.corporateForm.resetFields();
      this.corporateInformation.city = '';
    },
    // 新增用户select
    changeCity(val) {
      this.district(val,this.citydatas);
      // 区域反显
      const transition = this.district(val,this.citydatas)[0];
      this.corporateInformation.city = transition;
    },
    //  确认创建新增用户
    addUserSubmit() {
      this.$refs.corporateForm.validate(async (valid) => {
        if (valid) {
          await addCompanysApi.addCompanys(this.corporateInformation)
          .then(() => {
            this.$message.success('添加成功');
            this.addUserVisible = false;
            this.uptateCompanysList({
              page: this.page,
              pagesize: this.pagesize
            })
          })
          .catch(() => {
            this.$message.error('添加失败');
          })
          this.addUserVisible = false;
        } else {
          return false;
        }
      });
    },
    // 删除用户
    deleteCompany(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await addCompanysApi.deleteCompanys(id)
        .then(() => {
          this.$message.success('删除成功');
          this.uptateCompanysList({
            page: this.page,
            pagesize: this.pagesize
          })
        })
        .catch(() => {
          this.$message.error('删除失败');
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 状态
    async changeState(data) {
      await addCompanysApi.disabled({
        id: data.id,
        state: data.state === '启用' ? 0 : 1
      })
      // 刷新列表
      this.uptateCompanysList({
        page: this.page,
        pagesize: this.pagesize
      })
    },
    // 编辑用户
    editUserPopup(data) {
      addCompanysApi.queryMessage({
        id: data.id
      })
      this.compileUserVisible = true;
      this.compileUser.shortName = data.shortName;
      this.compileUser.company = data.company;
      this.compileUser.province = data.province;
      this.compileUser.city = data.city;
      this.compileUser.tags = data.tags;
      this.compileUser.remarks = data.remarks;
      this.compileUser.id = data.id;
      this.compileUser.number = data.number;
    },
    // 编辑用户表单反显
    changeCompileUser(val) {
      this.district(val,this.citydatas);
      // 区域反显
      const transition = this.district(val,this.citydatas)[0];
      this.compileUser.city = transition;
    },
    // 编辑用户表单提交
    compileUserSubmit() {
      this.$refs.compileUserForm.validate(async (valid) => {
        if (valid) {
          await addCompanysApi.updateCompanys(this.compileUser)
          .then(() => {
            this.$message.success('编辑成功');
            this.compileUserVisible = false;
            this.uptateCompanysList({
              page: this.page,
              pagesize: this.pagesize
            })
          })
          .catch(() => {
            this.$message.error('编辑失败');
          })
          this.compileUserVisible = false;
        } else {
          return false;
        }
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 16px;

  .main {
    padding-right: 12px;
    padding-top: 12px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background-color: #ffffff;

    .form-container {
      // grid布局
      display: grid;
      grid-template-columns: repeat(4, 25%);
      background-color: #ffffff;

      .bnt {
        margin-left: 60px;
      }

      .add-user {
        float: right;
      }
    }

    .record-container {
      background-color: #f4f4f5;
      border-radius: 4px;
      padding: 8px;
      margin-left: 26px;
      font-size: 13px;
      color: #909399;
      margin-bottom: 16px;
    }

  }

  // 弹窗
  .adduser-container {
    padding-right: 80px;

    .city {
      display: grid;
      grid-template-columns: repeat(2, 50%);
      // 有间隙
      grid-gap: 10px;
      padding-right: 10px;
    }

    .add-bnt {
      // 居中
      margin-left: 40px;
    }
  }

  .derive-list {
    padding-left: 26px;

    .delete-user:active {
      color: orange;
    }
  }
}


</style>
